package main

import (
	"fmt"
	"github.com/go-playground/validator"
	"github.com/labstack/echo/v4"
	"net/http"
	"time"
)

func main() {
	e := echo.New()
	e.HideBanner = true                                        // 隐藏启动横幅
	e.DisableHTTP2 = true                                      //关闭 HTTP/2 协议。
	e.Server.ReadTimeout = 10 * time.Minute                    //设置读取请求的最大时间。
	e.Server.WriteTimeout = 10 * time.Minute                   //设置写入响应的最大时间
	e.Validator = &CustomValidator{validator: validator.New()} //注册自定义参数校验器

	e.GET("/hello", func(c echo.Context) error {
		return c.String(200, "Hello, World!")
	})

	e.POST("/user", SaveUser)

	e.Logger.Fatal(e.Start(":80"))
}

// CustomValidator
// @Description: 自定义参数校验：负载执行数据验证。
type CustomValidator struct {
	validator *validator.Validate
}

// Validate
//
//	@Description: 实现接口的方法
//	@receiver cv
//	@param i
//	@return error
func (cv *CustomValidator) Validate(i interface{}) error {
	err := cv.validator.Struct(i)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("%v", err))
	}
	return nil
}

// User {
// "name": "lisi",
// "email": "13527403978@163.com"
// }
type User struct {
	Name  string `json:"name" validate:"required"`
	Email string `json:"email" validate:"required,email"`
}

func SaveUser(c echo.Context) error {
	u := new(User)
	if err := c.Bind(u); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if err := c.Validate(u); err != nil {
		return err
	}
	return c.JSON(http.StatusOK, u)
}
